import React, { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import { Empty, List } from 'antd';
export default (props) => {
  const {
    option,
    onLegendselectchanged,
    onClickChange,
    pieMouseOver,
    chartId,
    tabsCurrent,
    cycle,
  } = props;
  const chartIns = useRef(null);

  /**
   * 调用 resize  方法
   */
  const resizeAll = () => {
    chartIns.current.resize();
  };

  /**
   * 初始化图表组件
   */
  useEffect(() => {
    const element = document.getElementById(chartId);
    setTimeout(() => {
      chartIns.current = echarts.init(element);
      chartIns.current.on('legendselectchanged', (params) => {
        onLegendselectchanged &&
          onLegendselectchanged(params, chartIns.current, tabsCurrent);
      });

      chartIns.current.on('mouseover', (params) => {
        pieMouseOver && pieMouseOver(params, chartIns.current);
      });

      chartIns.current.on('click', (params) => {
        if (onClickChange) {
          onClickChange(params);
        }
      });

      window.removeEventListener('resize', resizeAll);
      if (chartIns.current) {
        window.addEventListener('resize', resizeAll);
        chartIns.current.resize();
        chartIns.current.setOption(option, true);
      }
    }, 20);
  }, []);

  /**
   * option 发生改变
   */
  useEffect(() => {
    window.removeEventListener('resize', resizeAll);
    if (chartIns.current) {
      window.addEventListener('resize', resizeAll);
      chartIns.current.resize();
      chartIns.current.setOption(option, true);

      chartIns.current.off('click'); //防止累计触发

      chartIns.current.on('click', (params) => {
        if (onClickChange) {
          onClickChange(params);
        }
      });
    }
  }, [option]);

  // return <div style={{ width: '100%', height: '100%' }} id={chartId} />;
  return (
    <>
      {Object.keys(option).length === 0 && (
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          style={{
            width: '100%',
            height: '100%',
            display: 'flex',
            alignItems: 'center',
            // border:'1px solid red',
            justifyContent: 'center',
            margin: 0,
          }}
        />
      )}
      <div
        style={{
          width: '100%',
          height: '100%',
          display: Object.keys(option).length !== 0 ? 'block' : 'none',
        }}
        id={chartId}
      />
    </>
  );
};
